// pages/product/details/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    buyNumber: 1,
    productBanners: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //options = {  id: '1027887380534054912' }
    if (!options) {
      this.handleError()
      return
    }
    var id = options.id
    if (!id) {
      this.handleError()
      return
    }
    this.setData({
      id: id
    })
    this.initDetails()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  handleError() {
    getApp().util.showToast('缺少参数')
    wx.switchTab({
      url: '/pages/product/index/index',
    })
  },
  initDetails() {
    getApp().network.get(getApp().api.productDetails.replace('$ID', this.data.id)).then(res => {
      wx.setNavigationBarTitle({
        title: res.name
      })
      var productBanners = []
      res.largeImage.split(',').forEach(item => {
        productBanners.push(getApp().util.getFileView(item))
      })
      this.setData({
        ...res,
        productBanners
      })
      console.log(this.data)
    })
  },
  goShop() {
    wx.switchTab({
      url: '/pages/product/index/index',
    })
  },
  onBuyNumberChange(event) {
    this.setData({
      buyNumber: event.detail
    });
  },
  doBuyProduct() {
    getApp().verifyLogin().then(res => {
      getApp().getOpenId().then(openId => {
        this.setData({
          openId: openId
        })
        this.doCreateOrder()
      })
    })
  },
  async doCreateOrder() {
    var orderNo = await getApp().network.post(getApp().api.createProductOrder, {
      productId: this.data.id,
      productNumber: this.data.buyNumber,
      openId: this.data.openId
    })
    getApp().getOpenId().then(openId => {
      this.doPay(orderNo, openId)
    })
  },
  doPay(orderNo, openId) {
    getApp().network.post(getApp().api.doPrepay, {
      openId: openId,
      tradeType: 'MINI_PROGRAM',
      payMethod: 'wx_v3',
      orderNo: orderNo
    }).then(res => {
      wx.requestPayment({
        timeStamp: res.timeStamp,
        nonceStr: res.nonceStr,
        package: res.packageVal,
        signType: res.signType,
        paySign: res.paySign,
        success: function (res) {
          wx.showToast({
            title: '支付成功！',
          })
        },
        fail: function (res) {}

      })
    })
  },
})